Getting Started with ASP.NET Core Web API - Middleware Order
TLDR
- The execution order of Middleware is critical to the correctness of an ASP.NET Core application.
- Exception handling (e.g.,
UseDeveloperExceptionPage) should take precedence over all other Middleware. UseRoutingmust be placed beforeUseCors,UseAuthentication, andUseAuthorization.UseCorsmust be placed beforeUseAuthenticationandUseResponseCachingto avoid known bugs.- If
UseStaticFilesinvolves cross-origin requests, culture, or compression, its position must be adjusted according to the corresponding Middleware. - Endpoint routing (e.g.,
MapControllers) must be placed at the very end of the pipeline.
Middleware Functionality Overview
In the ASP.NET Core pipeline, each Middleware plays a different role:
- Exception Handling:
UseDeveloperExceptionPageis used for reporting errors in the development environment;UseExceptionHandleris used to intercept exceptions thrown by subsequent Middleware. - Security:
UseHstsadds theStrict-Transport-Securityheader;UseHttpsRedirectionredirects HTTP requests to HTTPS. - Static Assets:
UseStaticFilesis responsible for handling static file requests. - Authentication and Authorization:
UseAuthenticationverifies user identity, whileUseAuthorizationchecks access permissions. - Routing and Endpoints:
UseRoutingis responsible for resolving routes, andUseEndpointsexecutes the final endpoint logic.
Recommended Middleware Order
The order of Middleware directly affects the request processing logic. The following is the recommended configuration order:
csharp
var app = builder.Build();
if (app.Environment.IsDevelopment()) {
app.UseMigrationsEndPoint();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
} else {
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseRateLimiter();
app.UseRequestLocalization();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseResponseCompression();
app.UseResponseCaching();
app.MapRazorPages();
app.MapDefaultControllerRoute();
app.Run();Common Pitfalls and Considerations
When configuring Middleware, be aware of the following order constraints for specific scenarios:
UseStaticFiles:
- When issues occur: When the application involves cross-origin requests, specific cultures, or requires compression caching.
- Recommendation: If using JavaScript to fetch cross-origin static files, it must be placed after
UseCors; if culture is involved, it must be placed afterUseRequestLocalization; if cached compressed files are required, it must be placed afterUseResponseCompressionandUseResponseCaching.
UseCors:
- When issues occur: When CORS settings conflict with caching or authentication mechanisms.
- Recommendation: It must be placed after
UseRoutingand beforeUseAuthentication. Additionally, placing it afterUseResponseCachingmay trigger the issue described at https://github.com/dotnet/aspnetcore/issues/23218.
UseRouting and RateLimiter:
- When issues occur: When the RateLimiter needs to rely on routing information.
- Recommendation: Unless the RateLimiter only uses global filters,
UseRoutingmust be placed beforeUseRateLimiter.
UseRequestLocalization:
- When issues occur: When subsequent Middleware needs to process requests based on culture.
- Recommendation: It must appear before any Middleware that checks the request culture.
Changelog
- Initial documentation created.